class Snack {

    head:HTMLElement;
    // HTMLCollection是一个集合，如果内容更新了，它会更新
    bodies:HTMLCollection;

    element:HTMLElement;
    constructor() {
         // 获取蛇的元素
        this.element = document.getElementById("snack")!;
        //querySelector会只取一个div,虽然snack有多个div
        this.head = document.querySelector("#snack > div") as HTMLElement;
        // querySelectorAll获取的是死的，需要我们实时刷新
        this.bodies = this.element.getElementsByTagName("div");
    }

    // 获取蛇头的坐标
    get X() {
        return this.head.offsetLeft;
    }
    get Y() {
        return this.head.offsetTop;
    }

    // 设置蛇头坐标
    set X(left:number) {
        if(this.X === left) {
            return
        }
        if (left<0 || left > 290) {
            throw new Error("蛇死了！！！")
        }
        if (this.bodies[1] && (this.bodies[1] as HTMLElement).offsetLeft === left) {
            console.log("水平方向掉头")
            if(left > this.X) {
            // 如果新值top比原来的this.Y大，说明，原来是往左走，现在要右调，此时我们要把它纠正，不让调
                left = this.X - 10
            } else {
                left = this.X + 10
            }
        }
        this.moveBody()
        this.head.style.left = left + "px";
        // 在设置完坐标后再调用
        this.checkHeadBody();
    }
    set Y(top:number) {
        if(this.Y === top) {
            return
        }
        if (top<0 || top > 290) {
            throw new Error("蛇死了！！！")
        }
        if (this.bodies[1] && (this.bodies[1] as HTMLElement).offsetTop === top) {
            console.log("竖直方向掉头")
            if(top > this.Y) {
            // 如果新值top比原来的this.Y大，说明，原来是往左走，现在要右调，此时我们要把它纠正，不让调
                top = this.Y - 10
            } else {
                top = this.Y + 10
            }
        }
        this.moveBody();
        this.head.style.top = top + "px";
        // 在设置完坐标后再调用
        this.checkHeadBody();
       
    }

    // 给蛇添加身体
    addBody(){
        // 给element添加一个div
        // beforeend表示在这个元素结束之前的位置
        this.element.insertAdjacentHTML("beforeend","<div></div>")
    }

    // 添加蛇移动
    moveBody() {
        // 注意：蛇每一节位置的改变，应该是由后往前改动，这样便于找到前一节的参考位置
        for(let i = this.bodies.length - 1; i > 0 ;i--) {
          let X = (this.bodies[i-1] as HTMLElement).offsetLeft;
          let Y = (this.bodies[i-1] as HTMLElement).offsetTop;
          (this.bodies[i] as HTMLElement).style.left = X + "px";
          (this.bodies[i] as HTMLElement).style.top = Y + "px";
        }
    }

    // 检查蛇头是否与身体相撞
    checkHeadBody() {
        for(let i = 1; i < this.bodies.length;i++) {
            let db = this.bodies[i] as HTMLElement
            if (this.X === db.offsetLeft && this.Y === db.offsetTop) {
                throw new Error("身体相撞了！！！")
            }
        }
    }

}

export default Snack